<?php
namespace app\admin\controller;
use app\admin\common\Base;
use app\admin\model\ServiceItem as ServiceItemModel;
use think\Db;
use think\facade\Request;
use think\Exception;
use app\admin\model\Client as ClientModel;
use app\admin\model\Order as OrderModel;
use app\admin\model\AdminUser as AdminUserModel;

/**
 * 客户控制器
 */
class Client extends Base{

    use \app\admin\traits\BaseFn;

    protected $model = null;

    public function initialize(){
        parent::initialize();
        $this->model = new ClientModel();
    }

    /**
     * 列表
     */
    public function index(){
        if(Request::isAjax()){

            list($where,$sort) = $this->buildQuery();
            if(empty($sort)) $sort = ['id'=>'desc'];    //【默认排序】


            //不同角色权限看到的数据不一样
            $userInfo = session('admin');
            $roleIds = explode(',', $userInfo['role_ids']);

            $wherePriv = [];
            if(in_array('1', $roleIds) || in_array('2', $roleIds)){ //【超级管理员】和【会计】角色查看客户资料无需条件限制
                ;
            }else if(count($roleIds)==1 && $roleIds[0] == '4'){ //【客服】角色只能查看自己的客户
                $wherePriv[] = ['add_user_id', '=', $userInfo['id'], ];
            }else if( in_array('3', $roleIds) ){ //【组长】角色可以看到自己和自己下属的客户
                $lowerLevelIds  = AdminUserModel::where(['leader'=> $userInfo['id']])->column('id');
                array_unshift($lowerLevelIds, $userInfo['id']);
                $wherePriv[] = ['add_user_id', 'in', $lowerLevelIds, ];
            }else{
                $wherePriv[] = ['1', '=', '0']; //其余角色不让看到数据
            }


            $list = $this->model->alias('t1')
                ->leftjoin('admin_user t2', 't1.add_user_id=t2.id')
                ->field('t1.*')
                ->field('t2.username,t2.nickname')
                ->where('t1.is_del', 0)
                ->where($where)
                ->where($wherePriv)     //按角色 过滤
                ->order($sort)
                ->paginate(Request::param('pageSize'));

            $list = $list->toArray();
            $data = [
                "total"=>$list['total'],
                'rows'=>$list['data'],
            ];
            return json($data);
        }
        return $this->fetch();
    }


    //新增订单
    protected function addOrder($clientId) {
        $orderModel = new OrderModel();
        $order = $this->request->post('order/a', []);

        $order['order_no'] = Date('ymdHi') . '0' . substr((string)(100*1000+ $clientId%100000),1);  //订单号生成规则： 误差 十万分之一
        $order['client_id'] = $clientId;
        $order['service_time'] = strtotime($order['service_time']);   //服务时间
        $order['order_status'] = 1;     //已接单
        $order['create_user_id'] = session('admin.id');
        $order['create_time'] = time();
        $res = $orderModel->allowField(true)->save($order);

        if($res){
            //下单数量 +1
            $this->model->where(['id'=>$clientId])->setInc('order_count');
        }

    }

    /**
     * 添加
     */
    public function add(){
        if(Request::isAjax()){
            $code = 0;
            $msg = 'success';
            $data = null;
            try{

                $post = Request::param();

                foreach ($post as $key=>$value){
                    if(substr($key,-4) === 'time'){
                        $post[$key] = strtotime($value);
                    }
                }
                $post['add_user_id'] = session('admin.id');
                $post['add_time'] = time();
                $res1 = $this->model->allowField(true)->save($post);


                if($res1){
                    $msg = "添加成功";

                    //新增订单
                    if( !empty($post['new_order']) ) {
                        $clientId = $this->model->id; //自增ID: 关联客户id
                        $this->addOrder($clientId);
                    }


                }else{
                    $code = 10001;
                    throw new Exception('添加失败');
                }

            }catch (Exception $e){
                $code = 10002;
                $msg = $e->getMessage();
            }

            return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);
        }

        //所有启用服务
        $srvItems = ServiceItemModel::where(['status'=>1])->field(['id', 'service_name'])
            ->order('id asc')->select();
        $this->assign('srvItems', $srvItems);

        return $this->fetch();
    }

    /**
     * 编辑
     */
    public function edit(){
        if(Request::isAjax()){
            $code = 0;
            $msg = 'success';
            $data = null;
            try{
                $clientId = Request::param('id');
                $where = [
                    'id'=> $clientId
                ];
                $update = Request::except('id');

                foreach ($update as $key=>$value){
                    if(substr($key,-4) === 'time'){
                        $update[$key] = strtotime($value);
                    }
                }

                $this->model->save($update,$where);
                $msg = "保存成功";

                //新增订单
                if( !empty($update['new_order']) ) {
                    $this->addOrder($clientId);
                }


            }catch (Exception $e){
                $code = 10002;
                $msg = $e->getMessage();
            }

            return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);
        }

        //所有启用服务
        $srvItems = ServiceItemModel::where(['status'=>1])->field(['id', 'service_name'])
            ->order('id asc')->select();
        $this->assign('srvItems', $srvItems);

        //编辑
        $where = Request::param();
        $data = $this->model->where($where)->find();
        $this->assign('data',$data);
        return $this->fetch();
    }


    //弹屏
    public function pop(){
        if(Request::isAjax()){
            $code = 0;
            $msg = 'success';
            $data = null;
            try{

                $update = Request::param();
                foreach ($update as $key=>$value){
                    if(substr($key,-4) === 'time'){
                        $update[$key] = strtotime($value);
                    }
                }
                if( !isset($update['id']) ){
                    //新增
                    $update['add_user_id'] = session('admin.id');
                    $update['add_time'] = time();

                    $Client = $this->model->create($update);
                    $clientId = $Client->id;


                }else{
                    $this->model->update($update);
                    $clientId = $update['id'];
                }
                $msg = "保存成功";


                //新增订单
                if( !empty($update['new_order']) ) {
                    $this->addOrder($clientId);
                }


            }catch (Exception $e){
                $code = 500;
                $msg = $e->getMessage();
            }

            return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);
        }

        //所有启用服务
        $srvItems = ServiceItemModel::where(['status'=>1])->field(['id', 'service_name'])
            ->order('id asc')->select();
        $this->assign('srvItems', $srvItems);



        $phone = $this->request->get('phone', '');
        $phone = trim($phone);
        $where = [
            'phone' => $phone,
            'is_del' => 0,
        ];
        $add_new = true;
        $data = $this->model->where($where)->find();
        if($data){
            $add_new = false;
            $tmpl = 'edit'; //编辑模板

        }else{
            $add_new = true;
            $data = [];
            $data['phone'] = $phone;
            $tmpl = 'add_pop'; //新增模板
        }

        $this->assign('data',$data);
        $this->assign('add_new', $add_new);
        return $this->fetch($tmpl);
    }


    //删除
    public function softDel(){
        $code = 0;
        $msg = 'success';
        $data = null;
        try{
            if(Request::isAjax()){
                $ids = Request::param('ids');
                if(empty($ids)){
                    $code = 10001;
                    throw new Exception('缺少参数');
                }
                //批量删除--软删除
                $delete_count = $this->model
                    ->where([
                        ['id','in',$ids]
                    ])->update(['is_del'=>1]);

                if($delete_count > 0){
                    $msg = '操作成功';
                }else{
                    $code = 10002;
                    throw new Exception('删除失败');
                }

            }else{
                $code = 10001;
                throw new Exception('请求失败');
            }
        }catch (Exception $e){
            $code = 10002;
            $msg = $e->getMessage();
        }

        return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);

    }

}
